package cn.chihanbao.zkWeb;

import io.github.yidasanqian.utils.JsonUtil;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ZkJdbc {
    private static JDBCParam jdbcParam = new JDBCParam("jdbc:mysql://linux123:3306/test?characterEncoding=utf-8&useSSL=false","root","12345678");
    private static Connection con =null;

    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient = new ZkClient( "linux121:2181" );
        System.out.println("zkClient is ready");
        zkClient.setZkSerializer( new ZkStrSerializer() );
        getNewConnection();
        boolean exists = zkClient.exists( "/jdbc" );
        if (!exists){
            zkClient.createPersistent( "/jdbc", JsonUtil.toJsonString(jdbcParam) );
        }
        zkClient.subscribeDataChanges( "/jdbc", new IZkDataListener() {
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println(s+"is changed"+o.toString());
                String str = o.toString();
                JDBCParam newJdbc = JsonUtil.toPojo(str, JDBCParam.class);
                System.out.println(newJdbc);
                jdbcParam.setPassword(newJdbc.getPassword());
                jdbcParam.setName(newJdbc.getName());
                jdbcParam.setUrl(newJdbc.getUrl());
                getNewConnection();
            }

            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s+"is deleted");
            }
        } );
        Thread.sleep(Integer.MAX_VALUE);
    }
    public static void getNewConnection(){
        try {
            if(con!=null){
                con.close();
            }
//            System.out.println(jdbcParam.getUrl() +jdbcParam.getName() );
            con = DriverManager.getConnection(jdbcParam.getUrl() , jdbcParam.getName() , jdbcParam.getPassword());
            System.out.println(String.format("连接成功：host：%s name:%s password:%s",jdbcParam.getUrl() , jdbcParam.getName() , jdbcParam.getPassword()));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
